package com.nineclock.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nineclock.common.constant.NcConstant;
import com.nineclock.common.entity.Result;
import com.nineclock.common.entity.UserInfo;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.common.oss.OssProperties;
import com.nineclock.common.threadlocal.CurrentUserHolder;
import com.nineclock.common.utils.BeanHelper;
import com.nineclock.message.enums.MessageTypeEnum;
import com.nineclock.message.pojo.NcMessage;
import com.nineclock.system.dto.*;
import com.nineclock.system.mapper.SysCompanyContactConfigMapper;
import com.nineclock.system.mapper.SysCompanyMapper;
import com.nineclock.system.mapper.SysCompanyUserMapper;
import com.nineclock.system.mapper.SysUserMapper;
import com.nineclock.system.pojo.SysCompany;
import com.nineclock.system.pojo.SysCompanyContactConfig;
import com.nineclock.system.pojo.SysCompanyUser;
import com.nineclock.system.pojo.SysUser;
import com.nineclock.system.service.SysCompanyContactConfigService;
import com.nineclock.system.service.SysCompanyService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class SysCompanyImpl implements SysCompanyService {
    @Autowired
    private SysCompanyMapper sysCompanyMapper;
    @Autowired
    OSS oss;
    @Autowired
    SysCompanyUserMapper sysCompanyUserMapper;
    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    OssProperties ossProperties;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Override
    public void applyJoinCompany(SysApplyJoinCompanyUserDTO sysApplyJoinCompanyUserDTO) {
        if(sysApplyJoinCompanyUserDTO == null){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        //根据用户id获取用户信息
        SysUser user = sysUserMapper.selectById(sysApplyJoinCompanyUserDTO.getUserId());
        if(user == null){
            throw new NcException(ResponseEnum.USER_NOT_FOUND);
        }

        user.setUsername(sysApplyJoinCompanyUserDTO.getUserName());
        user.setEmail(sysApplyJoinCompanyUserDTO.getEmail());
        user.setUpdateTime(new Date());
        user.setLastLoginCompanyId(sysApplyJoinCompanyUserDTO.getCompanyId());
        //更新到数据库
        sysUserMapper.updateById(user);

        //创建员工 数据
        SysCompanyUser companyUser = new SysCompanyUser();
        companyUser.setRemark(sysApplyJoinCompanyUserDTO.getApplyReason()); //申请加入的理由
        companyUser.setPost(sysApplyJoinCompanyUserDTO.getPost()); //职位
        companyUser.setTimeEntry(new Date());//入职时间
        companyUser.setEmail(sysApplyJoinCompanyUserDTO.getEmail());//邮箱
        companyUser.setMobile(sysApplyJoinCompanyUserDTO.getMobile());//手机号码
        companyUser.setCreateTime(new Date());//创建时间
        companyUser.setEnable((short)0);//是否可用， 管理员审批之后，可用
        companyUser.setCompanyName(sysApplyJoinCompanyUserDTO.getCompanyName());//企业名称
        companyUser.setCompanyId(sysApplyJoinCompanyUserDTO.getCompanyId()); //企业id
        companyUser.setUserId(sysApplyJoinCompanyUserDTO.getUserId());//用户id
        companyUser.setUserName(sysApplyJoinCompanyUserDTO.getUserName());//用户名
        companyUser.setImageUrl(sysApplyJoinCompanyUserDTO.getImageUrl()); //图片地址

        sysCompanyUserMapper.insert(companyUser);

        //获取 系统主管理员
        SysCompanyUser currentAdmin = sysCompanyUserMapper.queryCompanyManagerInfo(sysApplyJoinCompanyUserDTO.getCompanyId());
        // 推送消息 给主管理员
        NcMessage message = new NcMessage();
        message.setMessageType(MessageTypeEnum.COMPANY_APPLY.getType()); // 消息类型
        message.setAudience(MessageTypeEnum.COMPANY_APPLY.getAudience()); // 根据别名推送
        message.setTitle(MessageTypeEnum.COMPANY_APPLY.getTitle());//消息的标题
        message.setCreateTime(new Date());
        message.setCompanyId(sysApplyJoinCompanyUserDTO.getCompanyId() + "");
        message.setContent(sysApplyJoinCompanyUserDTO.getUserName() + " 正在申请加入企业，请及时审批"); //消息内容
        message.setUseStatus(0); //是否已经使用
        message.setTargets(Arrays.asList(currentAdmin.getMobile())); //目标人手机号码
        message.setApproveStatue(0); //审批状态
        message.setApplyUserId(sysApplyJoinCompanyUserDTO.getUserId()); //申请人 用户id
        message.setApplyUsername(sysApplyJoinCompanyUserDTO.getUserName()); //申请人用户名
        message.setApproveUserId(currentAdmin.getUserId()); //审批人用户id
        message.setApproveUsername(currentAdmin.getUserName());//审批人用户名

        rocketMQTemplate.convertAndSend( "messagePushTopic", message );
    }

    @Override
    public void allowedJoinCompany(SysAllowedJoinCompanyUserDTO sysAllowedJoinCompanyUserDTO) {
        if (sysAllowedJoinCompanyUserDTO.getApplyUserId()==null||
                sysAllowedJoinCompanyUserDTO.getApproved()==null||
                sysAllowedJoinCompanyUserDTO.getNotifyMsgId()==null) {
            throw new NcException(ResponseEnum.DATA_NOT_EXISTS);
        }
        LambdaQueryWrapper<SysCompanyUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysCompanyUser::getUserId, sysAllowedJoinCompanyUserDTO.getApplyUserId());
        wrapper.eq(SysCompanyUser::getCompanyId, CurrentUserHolder.get().getCompanyId());
        SysCompanyUser companyUser = sysCompanyUserMapper.selectOne(wrapper);
        companyUser.setRemark(sysAllowedJoinCompanyUserDTO.getRemark());
        if (sysAllowedJoinCompanyUserDTO.getApproved()) {
            companyUser.setEnable((short)1);
            sysCompanyUserMapper.updateById(companyUser);
        }
        rocketMQTemplate.convertAndSend("changeMongoPushTopic",sysAllowedJoinCompanyUserDTO.getNotifyMsgId());
        NcMessage message = new NcMessage();
        message.setMessageType(MessageTypeEnum.COMPANY_APPROVE.getType()); // 消息类型
        message.setAudience(MessageTypeEnum.COMPANY_APPROVE.getAudience()); // 根据别名推送
        message.setTitle(MessageTypeEnum.COMPANY_APPROVE.getTitle());//消息的标题
        message.setCreateTime(new Date());
        message.setCompanyId(CurrentUserHolder.get().getCompanyId() + "");
        if (sysAllowedJoinCompanyUserDTO.getApproved()){
            message.setContent("恭喜您，审核通过!"); //消息内容
        }else{
            message.setContent("很遗憾，审核失败!"); //消息内容
        }
        message.setUseStatus(1); //是否已经使用
        message.setTargets(Arrays.asList(companyUser.getMobile())); //目标人手机号码
        message.setApproveStatue(1); //审批状态
        message.setApplyUserId(companyUser.getUserId()); //申请人 用户id
        message.setApplyUsername(companyUser.getUserName()); //申请人用户名
        message.setApproveUserId(CurrentUserHolder.get().getId()); //审批人用户id
        message.setApproveUsername(CurrentUserHolder.get().getUsername());//审批人用户名

        rocketMQTemplate.convertAndSend("messagePushTopic", message);
    }


    @Override
    public List<SysCompanyDTO> queryCompanyByName(String keyword) {
        LambdaQueryWrapper<SysCompany> wrapper = new LambdaQueryWrapper<>();
        if(keyword != null){
            wrapper.like(SysCompany::getName, keyword);
        }

        List<SysCompany> companyList = sysCompanyMapper.selectList(wrapper);
        if(CollectionUtil.isEmpty(companyList)){
            throw new NcException(ResponseEnum.COMPANY_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(companyList, SysCompanyDTO.class);
    }
    @Override
    public Result<SysCompanyDTO> queryCompanyInfo() {
        UserInfo userInfo = CurrentUserHolder.get();
        Long companyId = userInfo.getCompanyId();
        SysCompany sysCompany = sysCompanyMapper.selectById(companyId);
        if (sysCompany == null) {
            throw new NcException(ResponseEnum.COMPANY_NOT_FOUND);
        }
        return Result.success(BeanHelper.copyProperties(sysCompany, SysCompanyDTO.class));
    }

    @Override
    public String updateCompanyLogo(MultipartFile file) throws IOException {
        if (file == null) {
            throw new NcException(ResponseEnum.FILE_UPLOAD_ERROR);
        }
        String contentType = file.getContentType();
        if (!NcConstant.ALLOWED_IMG_TYPES.contains(contentType)) {
            throw new NcException(ResponseEnum.INVALID_FILE_TYPE);
        }
        if (file.getSize() > NcConstant.maxFileSize) {
            throw new NcException(ResponseEnum.FILE_SIZE_EXCEED_MAX_LIMIT);
        }
        //file.getOriginalFilename() 获取原始文件名(包含后缀)
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String fileName = dateFormat.format(new Date()) + file.getOriginalFilename();
        //图片上传( 存储空间名称 ， 文件名， 文件流对象 )
        PutObjectResult putObjectResult = oss.putObject(ossProperties.getBucketName(), fileName, file.getInputStream());

        System.out.println("上传图片的结果：" + putObjectResult.getResponse());
        //host : https://%s.oss-cn-beijing.aliyuncs.com/
        // bucketName: nineclock-itheima
        //https://nineclock-itheima.oss-cn-beijing.aliyuncs.com/


        String filePath = String.format(ossProperties.getHost(), ossProperties.getBucketName()) + fileName;
        System.out.println("企业logo路径：" + filePath);
        return filePath;
    }

    @Override
    public void updateCompanyInfo(SysCompanyDTO sysCompanyDTO) {
        SysCompany sysCompany = BeanHelper.copyProperties(sysCompanyDTO, SysCompany.class);
        UserInfo userInfo = CurrentUserHolder.get();
        Long companyId = userInfo.getCompanyId();
        sysCompany.setId(companyId);
        sysCompanyMapper.updateById(sysCompany);
    }


}
